<?php
declare (strict_types = 1);

namespace app\controller\api\v1\user\course;

use app\controller\api\ApiController;
use app\service\logic\common\course\CategoryService;
use app\validate\common\course\CategoryValidate;
use think\App;
use think\response\Json;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class CategoryController extends ApiController
{
    protected $service;

    public function __construct(App $app, CategoryService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 显示资源列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $this->validate($params, CategoryValidate::class . '.index');

        $result = $this->service->getList($params, $search_fields, $search, ['byCreator']);
        return amis($result);
    }

    /**
     * 下拉菜单
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function options(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $drop = $this->service->getOptions($params, $search_fields, $search);
        return amis(['options' => $drop]);
    }

    /**
     * 显示资源
     *
     * @param $id
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function read($id): Json
    {
        $result = $this->service->getSimpleDetail($id);
        return amis($result);
    }
}
